package com.zbcz.erp.activity

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.activity.viewModels
import com.alibaba.android.arouter.launcher.ARouter
import com.zbcz.erp.databinding.ActivityLoginBinding
import com.zbcz.erp.sp.SharedPreferencesManager
import com.zbcz.erp.util.IS_TEST_MODE
import com.zbcz.erp.util.MAIN_ROUTE
import com.zbcz.erp.util.ToastUtils
import com.zbcz.erp.util.onSingleClick
import com.zbcz.erp.viewmodel.LoginViewModel

/**
 * erp
 */
class LoginActivity : BaseActivity() {

    private lateinit var mBinding: ActivityLoginBinding

    private val mLoginViewModel: LoginViewModel by viewModels()

    companion object {
        const val TAG = "LoginActivity"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        mBinding = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        super.onCreate(savedInstanceState)
        init()
    }

    fun init() {

        mBinding.tvLogin.onSingleClick {
//            startActivity(Intent(this@LoginActivity, MainActivity::class.java))
//            return@onSingleClick
            val account = mBinding.edAccount.text.toString().trim()
            val password = mBinding.edPassword.text.toString().trim()

            if (account.isEmpty()) {
                ToastUtils.show("请输入账户名")
                return@onSingleClick
            }

            if (password.isEmpty() || password.length < 6) {
                ToastUtils.show("密码应至少为6个字符")
                return@onSingleClick
            }
            mLoginViewModel.login(account, password)
        }
        mLoginViewModel.mLoginResponse.observe(this) { userInfo ->
            if (userInfo != null) {
                SharedPreferencesManager.saveUserInfo(this@LoginActivity, userInfo)
                Log.i(TAG, userInfo.toString())
                ToastUtils.show("登陆成功")
                //startActivity(Intent(this@LoginActivity, MainActivity::class.java))
                ARouter.getInstance().build(MAIN_ROUTE).navigation()
                finish()
            } else {
                ToastUtils.show("登陆失败")
            }
        }
        initTest()
    }

    private fun initTest() {
        //if (IS_TEST_MODE) {
        mBinding.edAccount.setText("admin")
        //Zbcz@202406
        mBinding.edPassword.setText("Zbcz@202406")
//
//        mBinding.edAccount.setText("chenqiaotong")
//        //Zbcz@202406
//        mBinding.edPassword.setText("zhangsan@123")
        //}
    }
}